//
//  LoginWithEmailViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/14.
//

import UIKit

class LoginWithEmailViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var loginView: LoginWithEmailView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.loginView = LoginWithEmailView().then({ make in
            make.delegate = self
        })
        self.view.addSubview(loginView)
        loginView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.creatClearNavigationBar(title: "Sign in")
    }

}

extension LoginWithEmailViewController{
    func loginWithEmailRequest(){
        self.hudView.hudView.startAnimation()
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<LoginData>,XGL_CustomRequestError>().request(LoginRequestAPI(requestAPI: .LoginWithPassword(password: self.loginView.password, email: self.loginView.email))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    let infor = XGL_userDataCacheManager.shared.token
                    infor.token = result.token
                    LoginInfor.share.infor = result
                    UserDefaults.standard.set(result.userId, forKey: XGL_AppInforCacheKey.share.userDefaultsAccountKey)
                    XGL_userDataCacheManager.shared.saveInfor(inforData: infor)
                    if result.profileStatus == 0 {
                        let vc = EditProfileHeaderViewController()
                        self.navigationController?.pushViewController(vc)
                    }else{
//                        self.dismiss(animated: true)
                        if let window = UIApplication.shared.currentWindow {
                            window.rootViewController = MainViewController
                        }
                    }
                    XGL_Notice.default.post(name: XGL_Notification.login.notificationName, object: nil)
                }
                break
            default:
                break
            }
        }
    }
}

extension LoginWithEmailViewController: LoginWithEmailDelegate{
    func createAccount() {
        let vc = LoginCreateAccountViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    func login() {
        self.loginWithEmailRequest()
    }
    
    func forgetPassword() {
        let vc = ForgetPasswordViewViewController()
        self.navigationController?.pushViewController(vc)
    }
}
